﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ExpressionTree表达式树_从表达式获取属性名 : System.Web.UI.Page
{

    /// <summary>
    /// 根据属性获取对应的属性名称
    /// </summary>
    /// <typeparam name="T">对象类型</typeparam>
    /// <param name="expr">需要获取的属性</param>
    /// <returns>属性名</returns>
    public static string GetPropertyName<T>(Expression<Func<T, object>> expr)
    {
        string propertyName = string.Empty;    //返回的属性名
                                               //对象是不是一元运算符
        if (expr.Body is UnaryExpression)
        {
            propertyName = ((MemberExpression)((UnaryExpression)expr.Body).Operand).Member.Name;
        }
        //对象是不是访问的字段或属性
        else if (expr.Body is MemberExpression)
        {
            propertyName = ((MemberExpression)expr.Body).Member.Name;
        }
        //对象是不是参数表达式
        else if (expr.Body is ParameterExpression)
        {
            propertyName = ((ParameterExpression)expr.Body).Type.Name;
        }
        return propertyName;
    }

    /// <summary>
    /// 从表达式中获取属性名
    /// </summary>
    /// <typeparam name="T">需要引用的类型</typeparam>
    /// <param name="expr">如p=>p.ABC</param>
    /// <returns></returns>
    public string GetPropertyNameA<T>(Expression<Func<T, object>> expr)
    {
        return ((MemberExpression)expr.Body).Member.Name;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write(GetPropertyNameA<ExpressionTree表达式树_从表达式获取属性名>(p => p.Adapter) + "<br/>");
        Response.Write(this.Items.GetPropertyName(p => p.Count));

    }
}

public static class uni
{
    /// <summary>
    /// 根据属性获取对应的属性名称
    /// </summary>
    /// <typeparam name="T">对象类型</typeparam>
    /// <typeparam name="K">对象数据的类型</typeparam>
    /// <param name="t">对象</param>
    /// <param name="expr">需要获取的属性</param>
    /// <returns>属性名</returns>
    public static string GetPropertyName<T, K>(this T t, Expression<Func<T, K>> expr)
    {
        string propertyName = string.Empty;    //返回的属性名
                                               //对象是不是一元运算符
        if (expr.Body is UnaryExpression)
        {
            propertyName = ((MemberExpression)((UnaryExpression)expr.Body).Operand).Member.Name;
        }
        //对象是不是访问的字段或属性
        else if (expr.Body is MemberExpression)
        {
            propertyName = ((MemberExpression)expr.Body).Member.Name;
        }
        //对象是不是参数表达式
        else if (expr.Body is ParameterExpression)
        {
            propertyName = ((ParameterExpression)expr.Body).Type.Name;
        }
        return propertyName;
    }
}